package org.linuxgears.BouncingBall.gui;

import javax.swing.*;

import org.linuxgears.BouncingBall.model.BallController;
import org.linuxgears.BouncingBall.model.BouncingBallModel;
import org.linuxgears.BouncingBall.painter.SimpleBallPainter;

import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

/**
 * Created by IntelliJ IDEA.
 * User: khilkeol
 * Date: 30 ���� 2010
 * Time: 10:27:44
 * To change this template use File | Settings | File Templates.
 */
public class BallCanvas extends JPanel implements MouseListener {
    
    public static int WIDTH = BouncingBallModel.WIDTH;
    public static int HEIGHT = BouncingBallModel.HEIGHT;
    
    private BouncingBallModel model;
    private BallController controller;

    public BallCanvas(BouncingBallModel model, BallController controller) {
        setPreferredSize(new Dimension(WIDTH, HEIGHT));
        this.model = model;
        this.controller = controller;

        Thread t = new Thread(new Updater(this));
        t.start();

        this.addMouseListener(this);
    }

    @Override
    public void paint(Graphics g) {
        super.paint(g);
        g.setColor(Color.black);
        g.fillRect(0, 0, WIDTH, HEIGHT);
        
        for (SimpleBallPainter painter: model.getPainters()) {
            painter.paint(g);
        }
    }

    @Override
    public void mouseClicked(MouseEvent e) {
        //To change body of implemented methods use File | Settings | File Templates.
    }

    @Override
    public void mousePressed(MouseEvent e) {
         
    	switch (e.getButton()) {
    	case MouseEvent.BUTTON1:
    		controller.selectBallAt(new Point(e.getX(), e.getY()));
    		break;
    	case MouseEvent.BUTTON3:
    		controller.moveSelectedBallTo(new Point(e.getX(), e.getY()));
    		break;
    	};
    }

    @Override
    public void mouseReleased(MouseEvent e) {
        //To change body of implemented methods use File | Settings | File Templates.
    }

    @Override
    public void mouseEntered(MouseEvent e) {
        //To change body of implemented methods use File | Settings | File Templates.
    }

    @Override
    public void mouseExited(MouseEvent e) {
        //To change body of implemented methods use File | Settings | File Templates.
    }

    private class Updater implements Runnable {
        public final static int DELAY = 1000/40; 
        private BallCanvas canvas;
        public Updater(BallCanvas canvas) {
            this.canvas = canvas;
        }
        @Override
        public void run() {
            try {
                while (true) {
                    this.canvas.repaint();
                    Thread.sleep(DELAY);
                }
            } catch (InterruptedException ex) {
                System.err.println(ex.getMessage());
                System.exit(1);
            }
        }
    }
}
